// AI服务前端集成
import axios from 'axios'

const API_BASE_URL = '' // 使用相对路径，通过Vite代理

export interface ChatMessage {
  role: 'user' | 'assistant' | 'system'
  content: string
}

export interface ChatRequest {
  messages: ChatMessage[]
  model?: string
  temperature?: number
  max_tokens?: number
  stream?: boolean
  search_enabled?: boolean  // 新增：是否启用搜索增强
}

export interface ChatResponse {
  content: string
  model: string
  timestamp: string
  error?: boolean
  search_results?: Array<{
    title: string
    url: string
    snippet: string
    source: string
  }>  // 新增：搜索结果
}

export interface AIModel {
  id: string
  name: string
  provider: string
  description: string
}

class AIService {
  private client = axios.create({
    baseURL: `${API_BASE_URL}/api`,
    timeout: 30000,
  })

  // 获取可用模型
  async getAvailableModels(): Promise<{ models: AIModel[]; default: string }> {
    try {
      const response = await this.client.get('/ai/models')
      console.log('Successfully fetched models:', response.data)
      
      // 适配豆包API响应格式
      if (response.data.models) {
        return {
          models: response.data.models,
          default: response.data.models[0]?.id || 'doubao-seed-1-6-250615'
        }
      }
      
      return response.data
    } catch (error) {
      console.error('获取模型列表失败:', error)
      // 返回豆包模型作为后备
      return {
        models: [{
          id: 'doubao-seed-1-6-250615',
          name: '豆包-基础版',
          provider: '字节跳动',
          description: '豆包大语言模型基础版本'
        }],
        default: 'doubao-seed-1-6-250615'
      }
    }
  }

  // 检查API状态
  async checkAPIStatus() {
    try {
      const response = await this.client.get('/ai/api-status')
      return response.data
    } catch (error) {
      console.error('检查API状态失败:', error)
      return { status: { has_any_key: false }, message: '无法连接到AI服务' }
    }
  }

  // 发送聊天消息
  async sendMessage(request: ChatRequest): Promise<ChatResponse> {
    try {
      console.log('Sending chat request to AI:', {
        model: request.model,
        messageCount: request.messages.length,
        searchEnabled: request.search_enabled,
        lastMessage: request.messages[request.messages.length - 1]?.content?.substring(0, 50) + '...'
      })
      
      const response = await this.client.post('/ai/chat', {
        messages: request.messages,
        model: request.model || 'doubao-seed-1-6-250615',
        search_enabled: request.search_enabled || false
      })
      
      console.log('Received AI response:', {
        model: response.data.model,
        contentLength: response.data.content?.length,
        timestamp: response.data.timestamp,
        hasSearchResults: !!response.data.search_results,
        searchResultsCount: response.data.search_results?.length || 0
      })
      
      return {
        content: response.data.content,
        model: response.data.model,
        timestamp: response.data.timestamp,
        error: false,
        search_results: response.data.search_results
      }
    } catch (error) {
      console.error('豆包AI对话失败:', error)
      
      // 返回错误响应
      return {
        content: `抱歉，豆包AI服务暂时不可用。请检查网络连接或稍后再试。\n\n提示：确保AI后端服务器运行在 http://localhost:8004`,
        model: request.model || 'error',
        timestamp: new Date().toISOString(),
        error: true
      }
    }
  }

  // 快速对话
  async quickChat(message: string, model: string = 'gpt-3.5-turbo') {
    try {
      const response = await this.client.post('/ai/chat/quick', null, {
        params: { message, model }
      })
      return response.data
    } catch (error) {
      console.error('快速对话失败:', error)
      throw error
    }
  }

  // 测试AI服务
  async testAIService() {
    try {
      const response = await axios.get(`${API_BASE_URL}/test/ai`)
      return response.data
    } catch (error) {
      console.error('测试豆包AI服务失败:', error)
      return {
        status: 'failed',
        message: error.message
      }
    }
  }

  // 健康检查
  async healthCheck() {
    try {
      const response = await axios.get(`${API_BASE_URL}/health`)
      return response.data
    } catch (error) {
      return { status: 'error', error: error.message }
    }
  }
}

export const aiService = new AIService()
export default aiService